package com.hckjsec.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hckjsec.cloud.domain.*;
import com.hckjsec.cloud.domain.sdk.ResultVerification;
import com.hckjsec.cloud.domain.verification.VerificationJwtView;
import com.hckjsec.cloud.domain.verification.VerificationLoginView;
import com.hckjsec.cloud.domain.verification.VerificationNumberView;
import com.hckjsec.cloud.domain.videoView.DetectAuthView;
import com.hckjsec.cloud.domain.view.BasicView;
import com.hckjsec.cloud.domain.view.CheckView;
import com.hckjsec.cloud.domain.wechatView.NewsHcView;
import com.hckjsec.cloud.domain.wechatView.NoticeHcView;
import com.hckjsec.cloud.domain.wechatView.OpenidView;
import com.hckjsec.cloud.domain.wechatView.WechatView;
import com.hckjsec.cloud.enums.publicParamEnum;
import com.hckjsec.cloud.service.*;
import com.hckjsec.common.aspose.AsposeWord;
import com.hckjsec.common.config.*;
import com.hckjsec.common.constant.Constants;
import com.hckjsec.common.core.redis.RedisCache;
import com.hckjsec.common.core.redis.SerialNumberUtils;
import com.hckjsec.common.dto.Result;
import com.hckjsec.common.enums.NumbereEnum;
import com.hckjsec.common.enums.SysFileTypeEnum;
import com.hckjsec.common.holiday.HolidayUtil;
import com.hckjsec.common.init.YwInitData;
import com.hckjsec.common.utils.*;
import com.hckjsec.common.utils.file.FileUploadUtils;
import com.hckjsec.common.utils.sign.Base64Converter;
import com.hckjsec.common.utils.uuid.BdOrcUtil;
import com.hckjsec.common.utils.uuid.IdUtils;
import com.hckjsec.website.domain.view.WebSiteMatterTableView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 此类处理微信小程序端请求的接口数据-内容管理
 */
@RestController
@RequestMapping("/wechat/api")
public class WxPublicApiArticleController {
    @Autowired
    private YwInitData ywInitData;

    @Autowired
    private IAppletsApplicantUserService appletsApplicantUserService;

    @Autowired
    private IAppletsPublicMechanismService appletsPublicMechanismService;

    @Autowired
    private IAppletsPublicMechanismDetailService appletsPublicMechanismDetailService;

    @Autowired
    private IAppletsPublicTeamService appletsPublicTeamService;

    @Autowired
    private IAppletsPublicNewsService appletsPublicNewsService;

    @Autowired
    private IAppletsPublicNotifyService appletsPublicNotifyService;

    @Autowired
    private IAppletsBusinessVerificationUserService appletsBusinessVerificationUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxAsyncService wxAsyncService;

    @Autowired
    private IAppletsBusinessVerificationService appletsBusinessVerificationService;

    @Autowired
    private IAppletsPublicTableService appletsPublicTableService;

    @Autowired
    private DetectPartnerAuthUtil detectPartnerAuthUtil;

    @Autowired
    private IAppletsSdkVerificationService appletsSdkVerificationService;

    @Autowired
    private IAppletsWechatMatterService appletsWechatMatterService;

    @Autowired
    private IAppletsWechatMatterTableService appletsWechatMatterTableService;
    //机构简介
    @PostMapping("/getMechanismAddress")
    public Result getMechanismAddress(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsPublicMechanismView appletsPublicMechanismView = new AppletsPublicMechanismView();
        AppletsPublicMechanism appletsPublicMechanism = new AppletsPublicMechanism(appletsConfig.getDeptId());
        List<AppletsPublicMechanism> appletsPublicMechanismList = appletsPublicMechanismService.selectAppletsPublicMechanismList(appletsPublicMechanism);
        if (!StringUtils.isEmpty(appletsPublicMechanismList)){
            AppletsPublicMechanism newAppletsPublicMechanism = appletsPublicMechanismList.get(0);
            appletsPublicMechanismView.setMechanismImg(newAppletsPublicMechanism.getMechanismImg());
            appletsPublicMechanismView.setContent(newAppletsPublicMechanism.getContent());
            List<AppletsPublicMechanismDetail> appletsPublicMechanismDetails = appletsPublicMechanismDetailService.selectAppletsPublicMechanismDetailList(new AppletsPublicMechanismDetail(newAppletsPublicMechanism.getMechanismId()));
            appletsPublicMechanismView.setAppletsPublicMechanismDetails(appletsPublicMechanismDetails);
        }
        return Result.success(appletsPublicMechanismView);
    }

    //团队介绍
    @PostMapping("/getMechanismTeam")
    public Result getMechanismTeam(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsPublicTeam appletsPublicTeam = new AppletsPublicTeam();
        appletsPublicTeam.setDeptId(appletsConfig.getDeptId());
        appletsPublicTeam.setState("true");
        List<AppletsPublicTeam> appletsPublicTeamList = appletsPublicTeamService.selectAppletsPublicTeamList(appletsPublicTeam);
        return Result.success(appletsPublicTeamList);
    }

    //团队介绍详情
    @PostMapping("/getMechanismTeamDetails")
    public Result getMechanismTeamDetails(@RequestBody WechatView wechatView)
    {
        Long teamId = wechatView.getTeamId();
        if (StringUtils.isNull(teamId)){
            return Result.cloud_602("teamId不能为空");
        }
        AppletsPublicTeam  appletsPublicTeam = appletsPublicTeamService.selectAppletsPublicTeamById(teamId);
        return Result.success(appletsPublicTeam);
    }

    //新闻动态
    @PostMapping("/getMechanismNews")
    public Result getMechanismNews(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        String pageSize = StringUtils.isHcNull(wechatView.getPageSize(),"");
        if("".equals(pageSize)){
            pageSize="10";
        }
        AppletsPublicNews appletsPublicNews = new AppletsPublicNews();
        appletsPublicNews.setDeptId(appletsConfig.getDeptId());
        appletsPublicNews.setState("true");
        List<AppletsPublicNews> appletsPublicNewsList=appletsPublicNewsService.selectAppletsPublicNewsList(appletsPublicNews);
        NewsHcView newsHcView = new NewsHcView();
        if (!StringUtils.isEmpty(appletsPublicNewsList)){
            int total=0;
            List<AppletsPublicNews> bannerList = new ArrayList<>();
            List<AppletsPublicNews> listData = new ArrayList<>();
            appletsPublicNewsList.forEach(kv->{
                if ("true".equals(kv.getIstop())){
                    bannerList.add(kv);
                }else{
                    listData.add(kv);
                }
            });
            total=listData.size();
            List<AppletsPublicNews> finallistData= new ArrayList<AppletsPublicNews>();
            if(listData.size()>Integer.valueOf(pageSize)){
                for(int i=0;i<Integer.valueOf(pageSize);i++){
                    if (listData.size()>i) {
                        finallistData.add(listData.get(i));
                    }
                }
            }else{
                finallistData=listData;
            }
            newsHcView.setBanner(bannerList);
            newsHcView.setListData(finallistData);
            newsHcView.setTotal(total);
        }
        return Result.success(newsHcView);
    }

    //新闻动态详情
    @PostMapping("/getMechanismNewsDetails")
    public Result getMechanismNewsDetails(@RequestBody WechatView wechatView)
    {
        Long newsId = wechatView.getNewsId();
        if (StringUtils.isNull(newsId)){
            return Result.cloud_602("newsId不能为空");
        }
        AppletsPublicNews appletsPublicNews =  appletsPublicNewsService.selectAppletsPublicNewsById(newsId);
        return Result.success(appletsPublicNews);
    }


    //通知公告
    @PostMapping("/getMechanismNotice")
    public Result getMechanismNotice(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        String pageSize = StringUtils.isHcNull(wechatView.getPageSize(),"");
        if("".equals(pageSize)){
            pageSize="10";
        }
        AppletsPublicNotify appletsPublicNotify = new AppletsPublicNotify();
        appletsPublicNotify.setDeptId(appletsConfig.getDeptId());
        appletsPublicNotify.setState("true");
        List<AppletsPublicNotify>  appletsPublicNotifyList = appletsPublicNotifyService.selectAppletsPublicNotifyList(appletsPublicNotify);
        NoticeHcView noticeHcView = new NoticeHcView();
        if (!StringUtils.isEmpty(appletsPublicNotifyList)){
            int total=appletsPublicNotifyList.size();
            List<AppletsPublicNotify> listData = new ArrayList<>();
            if(appletsPublicNotifyList.size()>Integer.valueOf(pageSize)){
                for(int i=0;i<Integer.valueOf(pageSize);i++){
                    if (appletsPublicNotifyList.size()>i) {
                        listData.add(appletsPublicNotifyList.get(i));
                    }
                }
            }else{
                listData=appletsPublicNotifyList;
            }
            noticeHcView.setTotal(total);
            noticeHcView.setListData(listData);
        }
        return Result.success(noticeHcView);
    }

    //通知公告详情
    @PostMapping("/getMechanismNoticeDetails")
    public Result getMechanismNoticeDetails(@RequestBody WechatView wechatView)
    {
        String openid = StringUtils.isHcNull(wechatView.getOpenid(),"");
        if("".equals(openid)){
            return Result.cloud_602("openid不能为空");
        }
        OpenidView openidView = appletsApplicantUserService.getOpenidView(openid,false);
        AppletsPublicNotify appletsPublicNotify = appletsPublicNotifyService.selectAppletsPublicNotifyById(wechatView.getNotifyId());
        return Result.success(appletsPublicNotify);
    }

    //身份核验登录
    @PostMapping("/verificationLogin")
    public Result verificationLogin(@RequestBody VerificationLoginView VerificationLoginView)
    {
        String appid = StringUtils.isHcNull(VerificationLoginView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appId不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        BasicView basicView=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(configId)),BasicView.class);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsBusinessVerificationUser finalVerificationUser = null;
        AppletsBusinessVerificationUser verificationUser = new AppletsBusinessVerificationUser();
        verificationUser.setConfigId(appletsConfig.getId());
        verificationUser.setDeptId(appletsConfig.getDeptId());
        verificationUser.setPassword(VerificationLoginView.getPassword());
        verificationUser.setUserName(VerificationLoginView.getLoginname().trim());
        List<AppletsBusinessVerificationUser>  verificationUserList = appletsBusinessVerificationUserService.selectAppletsBusinessVerificationUserList(verificationUser);
        if (!StringUtils.isEmpty(verificationUserList) ){
              finalVerificationUser=verificationUserList.get(0);
        }else{
            verificationUser.setUserName(null);
            verificationUser.setLoginName(VerificationLoginView.getLoginname().trim());
            List<AppletsBusinessVerificationUser>  verificationUserList2 = appletsBusinessVerificationUserService.selectAppletsBusinessVerificationUserList(verificationUser);
            if (!StringUtils.isEmpty(verificationUserList2) ){
                finalVerificationUser=verificationUserList2.get(0);
            }
        }
        if (StringUtils.isNull(finalVerificationUser)){
            return Result.cloud_602("用户名密码错误");
        }
        String uuid= IdUtils.simpleUUID();
        VerificationLoginView findVerificationLoginView = new VerificationLoginView();
        findVerificationLoginView.setAppid(appid);
        findVerificationLoginView.setConfigId(finalVerificationUser.getConfigId());
        findVerificationLoginView.setDeptId(finalVerificationUser.getDeptId());
        findVerificationLoginView.setDeptName(finalVerificationUser.getDeptName());
        findVerificationLoginView.setUserId(finalVerificationUser.getUserId());
        findVerificationLoginView.setLoginname(finalVerificationUser.getUserName());
        redisCache.setCacheObject(ComUtil.getVerificationKey(uuid),findVerificationLoginView, Constants.CAPTCHA_EXPIRATION, TimeUnit.HOURS);
        VerificationJwtView jwtView = new VerificationJwtView();
        jwtView.setToken(uuid);
        jwtView.setDeptName(finalVerificationUser.getDeptName());
        jwtView.setUserName(finalVerificationUser.getUserName());
        jwtView.setPhone(finalVerificationUser.getPhone());
        return Result.success(jwtView);
    }


    //获取biztoken
    @PostMapping("/verificationBizToken")
    public Result verificationBizToken(@RequestBody VerificationLoginView VerificationLoginView)
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(verificationLoginView.getConfigId())),BasicView.class);
        CheckView checkView=basicView.getIdentity();
        if (StringUtils.isNull(checkView)){
            return Result.cloud_602("身份核验未配置!");
        }
        String biztoken= DetectAuthUtil.getVerificationResult(checkView.getSecretId(),checkView.getSecretKey(),checkView.getRuleId());
        if("".equals(StringUtils.isHcNull(biztoken,""))){
            return Result.cloud_602("活体检测参数错误!");
        }
        DetectAuthView view=JSON.parseObject(biztoken, DetectAuthView.class);
        return Result.success(view);
    }

    //获取图片
    @PostMapping("/sendVerification")
    public Result sendVerification(@RequestBody VerificationLoginView VerificationLoginView) throws  Exception
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        String biztoken = StringUtils.isHcNull(VerificationLoginView.getBiztoken(),"");
        if("".equals(biztoken)){
            return Result.cloud_602("biztoken不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(verificationLoginView.getConfigId())),BasicView.class);
        CheckView checkView=basicView.getIdentity();
        wxAsyncService.getDetectVerificationAuthInfo("verification",verificationLoginView.getConfigId(),verificationLoginView.getDeptId(),biztoken,checkView,verificationLoginView);
        return Result.success();
    }

    //百度OCR
    @PostMapping("/idSdkCardOcr")
    public Result idSdkCardOcr(@RequestBody VerificationLoginView VerificationLoginView)
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(verificationLoginView.getConfigId())),BasicView.class);
        String idCardImg = StringUtils.isHcNull(VerificationLoginView.getIdCardImg(),"");
        if("".equals(idCardImg)){
            return Result.cloud_602("idCardImg不能为空");
        }
        FileInfoView fileInfoView= new FileInfoView();
        fileInfoView.setFilePath(idCardImg);
        fileInfoView.setPathFileName(JeeThinkConfig.getProfile()+idCardImg);
        BdIdCardResult idCardInfo  = BdOrcUtil.getIdCardInfo("front",fileInfoView.getPathFileName(),basicView.getBdocr().getAppid(),basicView.getBdocr().getAppkey(),basicView.getBdocr().getAppsecret());
        return Result.success(idCardInfo);
    }

    //SDK中获取biztoken
    @PostMapping("/verificationSdkData")
    public Result verificationSdkData(@RequestBody VerificationLoginView VerificationLoginView)
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(verificationLoginView.getConfigId())),BasicView.class);
        String  name = StringUtils.isHcNull(VerificationLoginView.getName(),"");
        if("".equals(name)){
            return Result.cloud_602("姓名不能为空");
        }
        String  idNo= StringUtils.isHcNull(VerificationLoginView.getIdNo(),"");
        if("".equals(idNo)){
            return Result.cloud_602("证件号码不能为空");
        }
        String userId = IdUtils.simpleUUID();
        String nonce = IdUtils.simpleUUID();
        String orderNo = IdUtils.simpleUUID();
        String keyLicence = basicView.getIdentity().getSecretKey();
        PartnerView partnerView = new PartnerView();
        partnerView.setApp_id(basicView.getIdentity().getRuleId());
        partnerView.setSecret(basicView.getIdentity().getSecretId());
        partnerView.setUserId(userId);
        partnerView.setNonce(nonce);
        detectPartnerAuthUtil.getAccessToken(partnerView);
        if (!"SUCCESS".equals(partnerView.getCode())){
            return Result.cloud_602("获取AccessToken失败!");
        }
        detectPartnerAuthUtil.getSignTicket(partnerView);
        if (!"SUCCESS".equals(partnerView.getCode())){
            return Result.cloud_602("获取SignTicket失败!");
        }
        partnerView.sign();
        detectPartnerAuthUtil.getNonceTicket(partnerView);
        if (!"SUCCESS".equals(partnerView.getCode())){
            return Result.cloud_602("获取NonceTicket失败!");
        }
        partnerView.userSign();
        PartnerUserView partnerUserView = new PartnerUserView();
        partnerUserView.setWebankAppId(partnerView.getApp_id());
        partnerUserView.setOrderNo(orderNo);
        partnerUserView.setName(name);
        partnerUserView.setIdNo(idNo);
        partnerUserView.setUserId(partnerView.getUserId());
        partnerUserView.setSign(partnerView.getSign());
        partnerUserView.setNonce(partnerView.getNonce());
        detectPartnerAuthUtil.send(partnerUserView,partnerView);
        if (!"SUCCESS".equals(partnerView.getCode())){
            return Result.cloud_602("发送验证失败，请检查姓名和身份证号是否正确!");
        }
        PartnerBackView partnerBackView = new PartnerBackView();
        partnerBackView.setFaceId(partnerView.getFaceId());
        partnerBackView.setAgreementNo(partnerUserView.getOrderNo());
        partnerBackView.setOpenApiAppId(partnerView.getApp_id());
        partnerBackView.setClientIp("47.114.95.164");
        partnerBackView.setGps("lgt=22.5044;lat=113.9537");
        partnerBackView.setOpenApiNonce(partnerView.getNonce());
        partnerBackView.setUserId(partnerView.getUserId());
        partnerBackView.setUserSign(partnerView.getUserSign());
        partnerBackView.setKeyLicence(keyLicence);
        partnerBackView.setVerifyMode("REFLECTION");
        AppletsSdkVerification appletsSdkVerification = new AppletsSdkVerification();
        appletsSdkVerification.setOrderNo(orderNo);
        appletsSdkVerification.setConfigId(verificationLoginView.getConfigId());
        appletsSdkVerification.setDeptId(verificationLoginView.getDeptId());
        appletsSdkVerification.setUserId(verificationLoginView.getUserId());
        appletsSdkVerification.setUsername(verificationLoginView.getLoginname());
        appletsSdkVerification.setOperatortime(DateUtils.getNowDate());
        appletsSdkVerification.setNonce(nonce);
        appletsSdkVerification.setCheckUserId(userId);
        appletsSdkVerification.setName(name);
        appletsSdkVerification.setIdNo(idNo);
        appletsSdkVerification.setSourcePhoto(VerificationLoginView.getIdCardImg());
        appletsSdkVerification.setState("0");
        String verNumber= SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_VERIFICATION_NUMBER);
        appletsSdkVerification.setVernumber(verNumber);
        int rows = appletsSdkVerificationService.insertAppletsSdkVerification(appletsSdkVerification);
        if (rows>0){
            return Result.success(partnerBackView);
        }else{
            return Result.cloud_602("未知错误!");
        }
    }

    //SDK中返回结果
    @PostMapping("/setResult")
    public Result setResult(@RequestBody VerificationLoginView VerificationLoginView) throws Exception
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(verificationLoginView.getConfigId())),BasicView.class);
        JSONObject object = JSON.parseObject(VerificationLoginView.getResultMsg());
        String res = object.getString("res");
        ResultVerification verification = JSON.parseObject(res.toString(),ResultVerification.class);
        AppletsSdkVerification appletsSdkVerification = appletsSdkVerificationService.selectAppletsSdkVerificationById(verification.getOrderNo());
        String  similarity = StringUtils.isHcNull(verification.getSimilarity(),"");//分值
        if (!"".equals(similarity)){
            PartnerView partnerView = new PartnerView();
            partnerView.setApp_id(basicView.getIdentity().getRuleId());
            partnerView.setSecret(basicView.getIdentity().getSecretId());
            partnerView.setNonce(appletsSdkVerification.getNonce());
            partnerView.setOrderNo(appletsSdkVerification.getOrderNo());
            partnerView.setUserId(appletsSdkVerification.getCheckUserId());
            detectPartnerAuthUtil.getAccessToken(partnerView);
            if (!"SUCCESS".equals(partnerView.getCode())){
                return Result.cloud_602("获取AccessToken失败!");
            }
            detectPartnerAuthUtil.getSignTicket(partnerView);
            if (!"SUCCESS".equals(partnerView.getCode())){
                return Result.cloud_602("获取SignTicket失败!");
            }
            partnerView.pullSign();
            PartnerResultView partnerResultView = detectPartnerAuthUtil.pull(partnerView);
            appletsSdkVerification.setState("1");
            appletsSdkVerification.setCode(partnerResultView.getCode());
            appletsSdkVerification.setMessage(partnerResultView.getMsg());
            appletsSdkVerification.setLiverate(partnerResultView.getResult().getLiveRate());
            appletsSdkVerification.setSimilarity(partnerResultView.getResult().getSimilarity());

            //图片转换
            FileInfoView OcrFrontFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            Base64Converter.generateFile(partnerResultView.getResult().getPhoto(),OcrFrontFileInfo.getPathFileName());
            appletsSdkVerification.setBestframe(OcrFrontFileInfo.getFilePath());
            //视频
            FileInfoView  videoFileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_VIDEO_MP4.getKey());
            Base64Converter.generateFile(partnerResultView.getResult().getVideo(),videoFileInfo.getPathFileName());
            appletsSdkVerification.setVideo(videoFileInfo.getFilePath());
            //生成核验文档
            Map<String,String> DocHt = new HashMap<>();
            DocHt.put("hybh",appletsSdkVerification.getVernumber());
            DocHt.put("jgmc",verificationLoginView.getDeptName());
            DocHt.put("xm",appletsSdkVerification.getName());
            Map<String, String> idNoMap = ComUtil.getBirAgeSex(appletsSdkVerification.getIdNo());
            DocHt.put("xb",idNoMap.get("sexCode") == "M"?"男":"女");
            DocHt.put("csrq",idNoMap.get("birthday"));
            DocHt.put("zjhm",appletsSdkVerification.getIdNo());
            DocHt.put("hyfz",appletsSdkVerification.getSimilarity());
            String jg="成功";
            if (!StringUtils.isHcNull(appletsSdkVerification.getCode(), "").equals("0")) {
                jg="失败";
            }
            DocHt.put("hyjg",jg);
            DocHt.put("hysj", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,appletsSdkVerification.getOperatortime()));
            DocHt.put("oneImg",OcrFrontFileInfo.getPathFileName());
            //合成
            String ywslj=JeeThinkConfig.getProfile()+"/"+"verification"+"/"+"htbgsdkvideo.doc";
            FileInfoView DocFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_DOC.getKey());
            String newdoclj=DocFileInfo.getPathFileName();
            boolean docmsg= AsposeWord.generateSdkReportVerification(ywslj, newdoclj, DocHt);
            if (docmsg){
                appletsSdkVerification.setReportdoc(DocFileInfo.getFilePath());
                FileInfoView PdfFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_PDF.getKey());
                String newpdflj=PdfFileInfo.getPathFileName();
                AsposeWord.word2pdf(newdoclj,newpdflj);
                appletsSdkVerification.setReportpdf(PdfFileInfo.getFilePath());
                FileInfoView  imgfileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
                String newimglj=imgfileInfo.getPathFileName();
                AsposeWord.generateReportToPng(newdoclj,newimglj);
                appletsSdkVerification.setReportimg(imgfileInfo.getFilePath());
            }
            appletsSdkVerificationService.updateAppletsSdkVerification(appletsSdkVerification);
        }else{
            appletsSdkVerification.setState("2");
            appletsSdkVerification.setCode(verification.getError().getCode());
            appletsSdkVerification.setMessage(verification.getError().getReason());
            appletsSdkVerificationService.updateAppletsSdkVerification(appletsSdkVerification);
        }
        return Result.success();
    }


    //获取SDK数量
    @PostMapping("/getVerificationSdkNumber")
    public Result getVerificationSdkNumber(@RequestBody VerificationLoginView VerificationLoginView) throws  Exception
    {
        VerificationNumberView verificationNumberView = new VerificationNumberView();
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        AppletsSdkVerification appletsSdkVerification = new AppletsSdkVerification();
        appletsSdkVerification.setUserId(verificationLoginView.getUserId());
        List<AppletsSdkVerification>  allList = appletsSdkVerificationService.selectAppletsSdkVerificationList(appletsSdkVerification);
        verificationNumberView.setAllNumber(allList.size());
        appletsSdkVerification.setBeginTime(DateUtils.getDate());
        List<AppletsSdkVerification>  todayList = appletsSdkVerificationService.selectAppletsSdkVerificationList(appletsSdkVerification);
        verificationNumberView.setTodayNumber(todayList.size());
        return Result.success(verificationNumberView);
    }

    //获取SDK数据
    @PostMapping("/getVerificationSdkList")
    public Result getVerificationSdkList(@RequestBody VerificationLoginView VerificationLoginView) throws  Exception
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        String pageSize = StringUtils.isHcNull(VerificationLoginView.getPageSize(),"");
        if("".equals(pageSize)){
            pageSize="10";
        }
        AppletsSdkVerification appletsSdkVerification = new AppletsSdkVerification();
        appletsSdkVerification.setUserId(verificationLoginView.getUserId());
        List<AppletsSdkVerification> allList = appletsSdkVerificationService.selectAppletsSdkVerificationList(appletsSdkVerification);

        List<AppletsSdkVerification> findAppletsSdkVerificationList = new ArrayList<>();
        if(allList.size()>Integer.valueOf(pageSize)){
            for(int i=0;i<Integer.valueOf(pageSize);i++){
                if (allList.size()>i) {
                    findAppletsSdkVerificationList.add(allList.get(i));
                }
            }
        }else{
            findAppletsSdkVerificationList=allList;
        }
        return Result.success(findAppletsSdkVerificationList);
    }

    //获取数量
    @PostMapping("/getVerificationNumber")
    public Result getVerificationNumber(@RequestBody VerificationLoginView VerificationLoginView) throws  Exception
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        VerificationNumberView verificationNumberView = new VerificationNumberView();
        AppletsBusinessVerification appletsBusinessVerification = new AppletsBusinessVerification();
        appletsBusinessVerification.setUserid(verificationLoginView.getUserId());
        appletsBusinessVerification.setVertype("verification");
        List<AppletsBusinessVerification> appletsBusinessVerificationList = appletsBusinessVerificationService.selectAppletsBusinessVerificationList(appletsBusinessVerification);
        verificationNumberView.setAllNumber(appletsBusinessVerificationList.size());
        appletsBusinessVerification.setBeginTime(DateUtils.getDate());
        List<AppletsBusinessVerification> appletsBusinessVerificationList2 = appletsBusinessVerificationService.selectAppletsBusinessVerificationList(appletsBusinessVerification);
        verificationNumberView.setTodayNumber(appletsBusinessVerificationList2.size());
        return Result.success(verificationNumberView);
    }

    //获取数据
    @PostMapping("/getVerificationList")
    public Result getVerificationList(@RequestBody VerificationLoginView VerificationLoginView) throws  Exception
    {
        String token = StringUtils.isHcNull(VerificationLoginView.getToken(),"");
        if("".equals(token)){
            return Result.cloud_602("token不能为空");
        }
        VerificationLoginView verificationLoginView  =redisCache.getCacheObject(ComUtil.getVerificationKey(token));
        if (StringUtils.isNull(verificationLoginView)){
            return Result.cloud_602("token已失效,请重新登录");
        }
        String pageSize = StringUtils.isHcNull(VerificationLoginView.getPageSize(),"");
        if("".equals(pageSize)){
            pageSize="10";
        }
        AppletsBusinessVerification appletsBusinessVerification = new AppletsBusinessVerification();
        appletsBusinessVerification.setUserid(verificationLoginView.getUserId());
        appletsBusinessVerification.setVertype("verification");
        List<AppletsBusinessVerification> appletsBusinessVerificationList = appletsBusinessVerificationService.selectAppletsBusinessVerificationList(appletsBusinessVerification);
        List<AppletsBusinessVerification> findAppletsBusinessVerificationList = new ArrayList<>();
        if(appletsBusinessVerificationList.size()>Integer.valueOf(pageSize)){
            for(int i=0;i<Integer.valueOf(pageSize);i++){
                if (appletsBusinessVerificationList.size()>i) {
                    findAppletsBusinessVerificationList.add(appletsBusinessVerificationList.get(i));
                }
            }
        }else{
            findAppletsBusinessVerificationList=appletsBusinessVerificationList;
        }
        return Result.success(findAppletsBusinessVerificationList);
    }

    //表格下载
    @PostMapping("/getTable")
    public Result getTable(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsPublicTable appletsPublicTable = new AppletsPublicTable();
        appletsPublicTable.setDeptId(appletsConfig.getDeptId());
        List<AppletsPublicTable> list = appletsPublicTableService.selectAppletsPublicTableList(appletsPublicTable);
        return Result.success(list);
    }


    //微官网事项材料
    @PostMapping("/getWechatMatter")
    public Result getWechatMatter(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long configId=ywInitData.getAppidByIdMap().get(appid);
        AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
        AppletsWechatMatter appletsWechatMatter = new AppletsWechatMatter();
        appletsWechatMatter.setDeptId(appletsConfig.getDeptId());
        appletsWechatMatter.setState("true");
        List<AppletsWechatMatter> list = appletsWechatMatterService.selectAppletsWechatMatterList(appletsWechatMatter);
        list.forEach(kv->{
            kv.setContent(null);
        });
        return Result.success(list);
    }

    //微官网事项材料-详情
    @PostMapping("/getWechatMatterDetail")
    public Result getWechatMatterDetail(@RequestBody WechatView wechatView)
    {
        String appid = StringUtils.isHcNull(wechatView.getAppid(),"");
        if("".equals(appid)){
            return Result.cloud_602("appid不能为空");
        }
        Long id = wechatView.getMattId();
        AppletsWechatMatter appletsWechatMatter = appletsWechatMatterService.selectAppletsWechatMatterById(id);
        Long mattId = appletsWechatMatter.getId();
        List<WebSiteMatterTableView> tableList = new ArrayList<>();
        AppletsWechatMatterTable appletsWechatMatterTable = new AppletsWechatMatterTable(mattId);
        List<AppletsWechatMatterTable> list = appletsWechatMatterTableService.selectAppletsWechatMatterTableList(appletsWechatMatterTable);
        list.forEach(kv->{
            WebSiteMatterTableView webSiteMatterTableView = new WebSiteMatterTableView();
            webSiteMatterTableView.setName(kv.getTableName());
            webSiteMatterTableView.setUrl(kv.getNamePath());
            tableList.add(webSiteMatterTableView);
        });
        appletsWechatMatter.setTableList(tableList);
        return Result.success(appletsWechatMatter);
    }
}
